<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="150px"
    >
      <el-form-item label="姓名" prop="cname">
        <el-input v-model="dataForm.cname" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="headUrl">
        <img :src="dataForm.headUrl" v-if="dataForm.id" style="width: 40px;height: 40px;">
        <img :src="dataForm.headUrl" v-if="!dataForm.id" style="width: 40px;height: 40px;">
        <el-upload
          class="upload-demo"
          :action="url"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传png文件且大小不超过250KB</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="年龄" prop="age">
        <el-input v-model="dataForm.age" placeholder="年龄"></el-input>
      </el-form-item>
      <el-form-item label="性别:" prop="sex">
        <el-radio v-model="dataForm.sex" label="1">男</el-radio>
        <el-radio v-model="dataForm.sex" label="2">女</el-radio>
        <el-radio v-model="dataForm.sex" label="0">未知</el-radio>
      </el-form-item>
      <el-form-item label="学校" prop="school">
        <el-input v-model="dataForm.school" placeholder="学校"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="birthplace">
        <el-input v-model="dataForm.birthplace" placeholder="地址"></el-input>
      </el-form-item>
      <el-form-item label="身份" prop="classPosition">
        <el-input v-model="dataForm.classPosition" placeholder="身份"></el-input>
      </el-form-item>
      <!-- <el-form-item label="活动排序编号" prop="sortIndex">
        <el-input v-model="dataForm.sortIndex" placeholder="活动排序编号"></el-input>
      </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        cname: "",
        headUrl: "",
        age: "",
        sex: "1",
        birthplace: "",
        school: "",
        classPosition: "",
        info: "",
        sortIndex: "",
        birthplace: ""
      },
      dataRule: {
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          { max: 12, message: "最长12个字符", trigger: "blur" }
        ],
        // headUrl: [{ required: true, message: "头像不能为空", trigger: "blur" }],
        age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
        sex: [{ required: true, message: "性别不能为空", trigger: "blur" }],
        school: [
          { required: true, message: "学校不能为空", trigger: "blur" },
          { max: 11, message: "最长11个字符", trigger: "blur" }
        ],
        classPosition: [
          { required: true, message: "身份不能为空", trigger: "blur" },
            {  max: 5, message: '最长5个字符', trigger: 'blur' }
        ],
        birthplace: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ],
        // sortIndex: [
        //   { required: true, message: "活动排序编号不能为空", trigger: "blur" }
        // ]
      },
      // 头像
      url: ""
    };
  },
  mounted() {
    this.url = this.$http.adornUrl(
      `/partner/partnertargetinfo/upload?token=${this.$cookie.get("token")}`
    );
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/partner/partnertargetinfo/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.cname = data.partnerTargetInfo.name;
              this.dataForm.headUrl = data.partnerTargetInfo.headUrl;
              this.dataForm.age = data.partnerTargetInfo.age;
              this.dataForm.sex = data.partnerTargetInfo.sex + "";
              this.dataForm.school = data.partnerTargetInfo.school;
              this.dataForm.classPosition =
                data.partnerTargetInfo.classPosition;
              this.dataForm.sortIndex = data.partnerTargetInfo.sortIndex;
              this.dataForm.birthplace = data.partnerTargetInfo.birthplace;
            }
          });
        }
      });
    },
    //上传头像
    handleAvatarSuccess(response, file, fileList) {
      this.fileList = fileList;
      this.successNum++;
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.$confirm("操作成功, 是否继续操作?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).catch(() => {
            this.visible = false;
          });
        }
        this.dataForm.headUrl = response.url;
      } else {
        this.$message.error(response.msg);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png';
      if (!isJPG) {
        this.$message.error("上传封面只能是 png 格式!");
      }
      const isSize = new Promise(function(resolve, reject) {
        let width = 270;
        let height = 330;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error("上传伴学对象必须是270*330!");
          return Promise.reject();
        }
      );
      return isJPG  && isSize;
    },
    // 表单提交
    dataFormSubmit(res, file) {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/partner/partnertargetinfo/${
                !this.dataForm.id ? "save" : "update"
              }`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              name: this.dataForm.cname,
              headUrl: this.dataForm.headUrl,
              age: this.dataForm.age,
              sex: this.dataForm.sex,
              birthplace: this.dataForm.birthplace,
              school: this.dataForm.school,
              classPosition: this.dataForm.classPosition,
              sortIndex: this.dataForm.sortIndex
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
